<template>
	<view>
		<uni-card>
			<uni-section title="任务基本信息" type="line">
				<uni-forms ref="form" :modelValue="formData" label-width="100px" :rules="formRules">
					<uni-forms-item label="任务名称" required name="name">
						<uni-easyinput v-model="formData.name" placeholder="请输入任务名称" />
					</uni-forms-item>
					<uni-forms-item label="房间" required name="roomId">
						<uni-data-select v-model="formData.roomId" :localdata="roomList" @change="getList(formData.equipId)"></uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="检查类型" required name="type">
						<uni-data-checkbox v-model="formData.type" :localdata="range"></uni-data-checkbox>
					</uni-forms-item>
					<uni-forms-item v-if="formData.type ==0" label="课程" required name="courseId">
						<uni-data-select v-model="formData.courseId" :localdata="courseList"></uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="执行人员" required name="executorId">
						<uni-data-select v-model="formData.executorId" :localdata="workers"></uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="初审人员" required name="reviewer1">
						<uni-data-select v-model="formData.reviewer1" :localdata="workers"></uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="复审人员" required name="reviewer2">
						<uni-data-select v-model="formData.reviewer2" :localdata="workers"></uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="备注">
						<uni-easyinput type="textarea" v-model="formData.notes" placeholder="请输入备注" />
					</uni-forms-item>
				</uni-forms>
			</uni-section>
		</uni-card>
		<uni-card v-if="formData.recordList.length">
			<uni-section title="检查项目" type="line">
				<uni-table ref="table" :loading="loading" border stripe emptyText="暂无更多数据" @selection-change="selectionChange">
					<uni-tr>
						<uni-th width="150" align="center">检查内容</uni-th>
						<uni-th width="205" align="center">检查结果</uni-th>
						<uni-th width="204" align="center">图片</uni-th>
					</uni-tr>
					<uni-tr v-for="(item, index) in formData.recordList" :key="index">
						<uni-td align="center">{{ item.content }}</uni-td>	
						<uni-td align="center">
							<uni-data-checkbox v-model="item.result" :localdata="rangeResult"></uni-data-checkbox>
						</uni-td>
						<uni-td align="center">
							<view>
								<button size="mini;" type="primary"
									style="border-radius: 5px;font-size:10px;width: 70px;" @click="uploadPic(index)"
									v-if="testArr[index].fileId == ''">
									上传图片</button> 
								<view v-else
									style="display: flex;flex-direction: row;align-items: center;">
									
									<view @click="openPic(item.url)" style="width: 50px;height: 50px;">
										<image mode="aspectFit" :src="item.url"
											style="width: 50px;height: 50px;"></image>
									</view>
									<uni-icons type="close" size="20" color="#acacac;"
										@click="deletePic(index)"></uni-icons>
								</view>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
			</uni-section>
		</uni-card>
		<button type="primary" @click="submit()">提交</button>
		<uni-popup ref="IMAGE">
			<view>
				<image mode="aspectFit" :src="picUrl"></image>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import { listRoomAll } from '@/common/api/device'
	import { listItemAll, update, add, getById } from '@/common/api/scene'
	import { workersAll, upload } from '@/common/api/user'
	import { listCourseAll } from '@/common/api/course.js'
	export default {
		data() {
			return {
				// 表单参数
				formData: {
					name: '',
					roomId: null,
					type: 0,
					courseId: null,
					executorId: '',
					reviewer1: '',
					reviewer2: '',
					recordList: []
				},
				range: [{"value": 0,"text": "按课程"	},{"value": 1,"text": "按周"}],
				rangeResult: [{"value": -1,"text": "合格"	},{"value": 1,"text": "不合格"}],
				formRules: {
					name : {
						rules: [{
							required: true,
							errorMessage: '任务名称不能为空'
						}]
					},
					roomId : {
						rules: [{
							required: true,
							errorMessage: '设备不能为空'
						}]
					},
					type : {
						rules: [{
							required: true,
							errorMessage: '点检类型不能为空'
						}]
					},
					courseId : {
						rules: [{
							required: true,
							errorMessage: '课程不能为空'
						}]
					},
					executorId : {
						rules: [{
							required: true,
							errorMessage: '初审人员不能为空'
						}]
					},
					reviewer1 : {
						rules: [{
							required: true,
							errorMessage: '初审人员不能为空'
						}]
					},
					reviewer2 : {
						rules: [{
							required: true,
							errorMessage: '复审人员不能为空'
						}]
					},
				},
				roomList: [],
				loading: false,
				tableData: [],
				workers: [],
				courseList: [],
				picUrl: '',
				testArr: []
			}
		},
		components: {
		},
		onLoad(option) {
			if(option.id) {
				getById(option.id).then(res => {
					console.log(res, 'response')
					this.formData = res.data
				})
			}			
			listRoomAll().then(res => {
				console.log(res, 'room...')
				this.roomList = res.data.map(item => ({
					value: item.roomId,  // 使用原数组中的 id 作为 value
					text: item.roomName // 使用原数组中的 sport 作为 text
				}));
			})
			listCourseAll().then(res => {
				console.log(res, 'course...')
				this.courseList = res.data.map(item => ({
					value: item.courseId, 
					text: item.courseName
				}));
			})
			workersAll().then(res => {
				console.log(res, 'workers...')
				this.workers = res.data.map(item => ({
					value: item.staffId, 
					text: item.staffName
				}));
			})
		},
		methods: {
			// 获取该设备点检项目
			getList(id) {
				console.log(id)
				listItemAll(id).then(res => {
					console.log(res, 'items')
					this.formData.recordList = res.data.rows
					this.formData.recordList.forEach(item => {
						item.result = 1
						item.fileList = []
					})
					for(let i = 0 ; i < res.data.rows.length; i++) {
						let item = {
							fileId: '',
							name: '',
							url: ''
						}
						this.testArr.push(item)
					}
					console.log(this.formData.recordList, this.testArr, '...')
				})
			},
			submit() {
				this.$refs['form'].validate().then(res => {
					this.formData.recordList.forEach((item, index) => {
						item.fileList.push(this.testArr[index])
						item.itemId = item.id
					})
					console.log('success recordList', this.formData.recordList);
					if(this.formData.id) {
						// 编辑
						update(this.formData).then(res => {
							console.log(res, 'upload')
						})
					} else {
						// 新增
						add(this.formData).then(res => {
							console.log(res, 'upload')
						})
					}
				}).catch(err => {
					console.log('err', err);
				})
			},
			uploadPic(index) {
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const imagePath = res.tempFilePaths[0]
						// 从本地获取 token
						const token = uni.getStorageSync('App-Token');
						uni.uploadFile({
							url: '/api/system/file/upload',
							filePath: imagePath,
							name: 'file',
							timeout: 60000,
							method: 'POST',
							header: {
								'Authorization': token ? `Bearer ${token}` : '', // 添加 token
							},
							success: (uploadFileRes) => {
								const data = JSON.parse(uploadFileRes.data)
								// console.log('data', data)
								if (data.success) {
									// this.testArr[index] = {
									// 	fileId: data.data.fileId,
									// 	name: data.data.logicalName,
									// 	url: data.data.prePath + data.data.fileName
									// }
									this.testArr[index].fileId = data.data.fileId,
									this.testArr[index].name = data.data.logicalName,
									this.testArr[index].url = data.data.fileName,
									console.log(this.testArr, '?')
								} else {
									uni.showToast({
										title: '上传失败',
										icon: 'none',
									})
								}
							},
							fail: (err) => {
								console.log('上传失败', err)
								uni.showToast({
									title: '上传失败',
									icon: 'none',
								})
							}
						})
					},
					fail: (err) => {
						console.log('选择图片失败', err)
					}
				})
			},
			openPic(url) {
				this.picUrl = url
				this.$refs.IMAGE.open()
			},
			deletePic(index) {
				this.formData.recordList[index].fileList = [{
					fileId: '',
					name: '',
					url: ''
				}]
			}
			
		}
	}
</script>

<style>
	button {
		margin: 15px;
	}
</style>